<?php

namespace app\order\logic;

use app\common\library\Excel;
use app\data\util\MqQueueName;
use app\systems\logic\MqTaskPushLogic;
use think\facade\Config;
use Throwable;
use app\common\service\ConstantOrderService;
use app\order\model\Orderwh as OrderWhModel;
use think\facade\Db;

class OrderWhLogic
{
    protected $model = null;

    public function __construct()
    {
        $this->model = new OrderWhModel();
    }

    public function getOrderWhList($params = [])
    {

        $orderId         = $params['order_id'] ?? '';
        $status          = $params['status'] ?? '';
        $seller_sku      = $params['skuinfo'] ?? '';
        $tracking_number = $params['tracking_number'] ?? '';
        $buyer_name      = $params['name'] ?? '';
        $createtime      = $params['createtime'] ?? '';
        $sendTime        = $params['sendTime'] ?? '';
        $limit           = $params['limit'] ?? 10;

        $where = [];
        $order = ['createtime' => 'desc', 'id' => 'desc'];

        if ($orderId) {
            $order_ids = trim($orderId);
            $order_ids = array_filter(array_map('trim', explode("\n", $order_ids)));
            if (!empty($order_ids)) {
                $where[] = ['order_id', 'in', $order_ids];
            }
        }


        if($status=='0'){
            $where[] = ['tracking_beforehand', '=', 0];
        }else{
            if($status){
                switch($status){
                    case 10:
                        $where[] = ['tracking_beforehand', '=', 0];
                        break;
                    case 1:
                        $where[] = ['tracking_beforehand', '=', 1];
                        break;
                    case 2:
                        $where[] = ['tracking_beforehand', '=', 2];
                        break;
                    case 3:
                        $where[] = ['tracking_beforehand', '=', 3];
                        break;
                    case 4:
                        $where[] = ['tracking_beforehand', '=', 4];
                        break;
                    case 5:
                        $where[] = ['tracking_beforehand', '=',5];
                        break;
                    case 6:
                        $where[] = ['tracking_beforehand', '=', 6];
                        break;
                }
            }else{
                $where[] = ['tracking_beforehand', '<>', 6];
            }
        }



        if ($seller_sku) {
            $where[] = ['skuinfo', 'like', '%' . $seller_sku . '%'];
        }
        if ($tracking_number) {
            $where[] = ['tracking_number', 'like', '%' . $tracking_number . '%'];
        }
        if ($buyer_name) {
            $where[] = ['name', 'like', '%' . $buyer_name . '%'];
        }
        if ($createtime) {
            $createtimeArr = explode(',', $createtime);
            $where[] = ['createtime', '>=', strtotime($createtimeArr[0])];
            $where[] = ['createtime', '<=', strtotime($createtimeArr[1])];
        }


        if ($sendTime) {
            $sendTimeArr = explode(',', $sendTime);
            $where[] = ['updatetime', '>=', strtotime($sendTimeArr[0])];
            $where[] = ['updatetime', '<=', strtotime($sendTimeArr[1])];
        }



        $res = $this->model
            ->where($where)
            ->order($order)
            ->paginate($limit);

        $list = $res->items()?:[];
        $info = Config::get('Logisticskey.' . 'warehouse_arr');

        if($list){
             foreach($list as $k=>$v){
                 $list[$k]['warehouse_name']=  $v['warehouse_id'] ? $info[$v['warehouse_id']]:'';
                 $list[$k]['sendTime']      =  $v['updatetime'] ? date("Y-m-d H:i:s", $v['updatetime']):'';
             }
        }

        $data = [
            'list'   => $list,
            'total'  => $res->total(),
        ];
        return json(DefaultResponse(200, true, '获取成功', $data));
    }

    public function editOrder($project, $data)
    {
        if (!$data) {
            return json(DefaultResponse(201, false, '参数不能为空!', null));
        }

        $result = false;
        $this->model->startTrans();
        try {
            $result = $project->save($data);
            $this->model->commit();
        } catch (Throwable $e) {
            $this->model->rollback();
            return json(DefaultResponse(201, false, $e->getMessage(), null));
        }
        if ($result !== false) {
            return json(DefaultResponse(200, true, '更新成功!', null));
        } else {
            return json(DefaultResponse(201, false, '更新失败!', null));
        }
    }

    public static function insertOrderWhLog($log)
    {

        $arr['status']       = $log['code']??'';
        $arr['msg']          = $log['msg']??'';
        $arr['data']         = $log['data']??'';
        $arr['order_id']     = $log['order_id']??'';
        $arr['shop_id']      = $log['shop_id']??'';
        $arr['warehouse_id'] = $log['warehouse_id']??'';
        $arr['return']       = $log['return0']??'';
        $arr['time']         = time();
        Db::name('orderwh_log')->insert($arr);
    }

    /**
     * @desc  网红小店-自动发货
     * @param $params
     * @return \think\response\Json
     */
    public function automaticShipping($params = [])
    {
        $ids          = $params['ids'];
        $warehouse_id = $params['warehouse_id'];
        if (empty($warehouse_id)) {
            return json(DefaultResponse(201, true, '仓库数据错误请刷新'));
        }
        $ids   = is_array($ids) ? $ids : explode(',', $ids);
        $items = $this->model->where("id", "in", $ids)->select();
        $items = objectToArray($items);
        if(!$items)   return json(DefaultResponse(201, true, '暂无基础数据'));
        foreach ($items as $item) {
                if (in_array($item['tracking_beforehand'], [0,1,2])) {
                    if (in_array($warehouse_id, [3,4])) {
                        $item['warehouse_id'] = $warehouse_id;
                        // 队列处理
                        MqTaskPushLogic::mq_task_push(
                            '',
                            MqQueueName::QUEUE_WH_ORDER_SHIPPING_QUEUE,
                            $item,
                            false
                        );
                    }
                }
        }

        //直接触发MQ消费 2024-05-14
        (new OrderBtLogic())->getCrontab();
        return json(DefaultResponse(200, true, '操作成功!'));
    }

    /**
     * 网红小店-暂无渠道发货-标记
     * @param $params
     * @return \think\response\Json
     */
    public function markerOrder($params = [])
    {
        $ids   = $params['ids'];
        $ids   = is_array($ids) ? $ids : explode(',', $ids);
        $items = $this->model->where("id", "in", $ids)->select();
        $items = objectToArray($items);
        if(!$items)   return json(DefaultResponse(201, true, '暂无数据'));
        $update = [];
        foreach ($items as  $item) {
            $update[] = [
                'id'                        => $item['id'],
                'tracking_beforehand'       => 6,
                'order_status'              => "hidden",
                'time'                      => time(),
            ];
        }
        if (!empty($update)) {
            $this->model->saveAll($update);
        }
        return json(DefaultResponse(200, true, '操作成功!'));
    }

    /**
     * 订单导出
     * @param $params
     * @return string
     */
    public function exportOrder($params = [])
    {
        $orderId         = $params['order_id'] ?? '';
        $status          = $params['status'] ?? '';
        $seller_sku      = $params['skuinfo'] ?? '';
        $tracking_number = $params['tracking_number'] ?? '';
        $buyer_name      = $params['name'] ?? '';
        $createtime      = $params['createtime'] ?? '';
        $limit           = $params['limit'] ?? 10;

        $where = [];
        $order = ['createtime' => 'desc', 'id' => 'desc'];

        if ($orderId) {
            $order_ids = trim($orderId);
            $order_ids = array_filter(array_map('trim', explode("\n", $order_ids)));
            if (!empty($order_ids)) {
                $where[] = ['order_id', 'in', $order_ids];
            }
        }

        if ($seller_sku <> '') {
            $where[] = ['skuinfo', 'like', '%' . $seller_sku . '%'];
        }
        if ($tracking_number <> '') {
            $where[] = ['tracking_number', 'like', '%' . $tracking_number . '%'];
        }
        if ($buyer_name <> '') {
            $where[] = ['name', 'like', '%' . $buyer_name . '%'];
        }
        if ($createtime <> '') {
            $createtimeArr = explode(',', $createtime);
            $where[] = ['createtime', '>=', strtotime($createtimeArr[0])];
            $where[] = ['createtime', '<=', strtotime($createtimeArr[1])];
        }

        $list = $this->model
            ->where($where)
            ->order($order)
            ->select()
            ->toArray();
        $warehouseInfo= Config::get('Logisticskey.' . 'warehouse_arr');
        foreach ($list as $k => $v) {
            $list[$k]['warehouse_name']=  $v['warehouse_id'] ? $warehouseInfo[$v['warehouse_id']]:'';
        }

        $header[] = ['订单号', 'order_id'];
        $header[] = ['创建时间', 'createtime'];
        $header[] = ['达人姓名', 'name'];
        $header[] = ['链接', 'link'];
        $header[] = ['发货SKU', 'skuinfo'];
        $header[] = ['邮箱', 'buyer_email'];
        $header[] = ['电话', 'phone_number'];
        $header[] = ['详细地址', 'address_detail'];
        $header[] = ['邮编', 'postal_code'];
        $header[] = ['省份', 'state'];
        $header[] = ['市区', 'city'];
        $header[] = ['县', 'county'];
        $header[] = ['备注', 'remarks'];
        $header[] = ['邮编', 'postal_code'];
        $header[] = ['跟踪号', 'tracking_number'];
        $header[] = ['仓库', 'warehouse_name'];

        $fileName = "export_orderwh_" . time();
        return Excel::exportData($list, $header, $fileName, 'xlsx');
    }

    /**
     * 导入网红订单
     * @param $url
     * @return string
     */
    public function insertOrderWh($url)
    {
        $data         = Excel::getExcelData('.' . '/' . $url);
        $excelData    = isset($data[0]) ? $data[0] : $data;
        if(!$excelData)   return json(DefaultResponse(201, false, '暂无数据!', null));
        $excelData    = filterArr($excelData);
        $arr_insert   = [];
        foreach ($excelData as $k => $value) {
            $order_id     = date('YmdHms') . rand(11, 99) . $k;
            $arr_insert[] = [
                'name'           => $value['A'] ?? 0,
                'link'           => $value['B'] ?? '',
                'skuinfo'        => $value['C'] ?? '',
                'buyer_email'    => $value['D'] ?? '',
                'phone_number'   => $value['E'] ?? '',
                'address_detail' => $value['F'] ?? '',
                'state'          => $value['G'] ?? '',
                'city'           => $value['H'] ?? '',
                'county'         => $value['I'] ?? '',
                'remarks'        => $value['J'] ?? '',
                'postal_code'    => $value['K'] ?? 0,
                'order_id'       => $order_id,
                'createtime'     => time(),
            ];
        }
        $this->model->insertAll($arr_insert);
        return  '导入成功';
    }


    /**
     * @desc  重复发送的转为已处理
     * @date  2024-05-23
     * @author luckyXiong
     */
    public function endShipping($params=[]){
        $id        = $params['ids'];
        $status    = $params['status']??'';
        $ids       = is_array($id) ? $id : explode(',', $id);
        Db::name('orderwh')->whereIn('id', $ids)->update(
            [
                'tracking_beforehand'       => 4,
                'msg'                       => '发货成功',
                'updatetime'                => time(),
            ]
        );
    }








}
